
// 导入 component（组件）
import React, { Component } from 'react';
// 导入 组件 appRegistry、View、Text、ListView(列表) 、 StyleSheet(样式表)、Image、TouchableHighlight(按钮)、AlertIOS、RefreshControl  
import { AppRegistry, View, Text, ListView, StyleSheet, Image, TouchableHighlight, AlertIOS, RefreshControl, ActivityIndicator } from 'react-native';
// 导入 头文件 
import WorkflowDetail from './WorkflowDetail'

//export default关键字,它的意思是导出(export)当前组件，以允许其他组件引入(import)和使用当前组件
export default class WorkflowList extends Component {
  // 初始化模拟数据 ,以下是ListView的 默认用法
  constructor(props) {
    super(props);
    
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    ds.cloneWithRows([
        'John', 'Joel', 'James', 'Jimmy', 'Jackson', 'Jillian', 'Julie', 'Devin'
      ]);
    this.state = {
      dataList:[],  //列表原始数据
      dataSource: ds,
      isRefreshing:false,
      loaded:1,     //0：隐藏 1：加载中 2：加载完成
      page:1,
    };
  }

  componentDidMount() {
    this._headerRefresh();
  }

  componentWillUnmount() {
  // 如果存在this.timer，则使用clearTimeout清空。
  // 如果你使用多个timer，那么用多个变量，或者用个数组来保存引用，然后逐个clear
    this.timer && clearTimeout(this.timer);
  }

  onEndReached() {

    if (this.state.loaded == 0) {
        this.setState({loaded:1});
        this.timer = setTimeout( () => this._loadData(false), 1000);
    }
  }

  _loadData(covered) {
    fetch('http://121.199.53.201:7008/Liems/webservice/getWorkFlowTaskDoneList?langId=CHZ&limit=20&page='+ this.state.page +'&searchParams=%7B%22endDtm%22%3A%22%22%2C%22type%22%3A%221%22%2C%22content%22%3A%22%22%2C%22pgmId%22%3A%22B1OAM08100%22%2C%22tblName%22%3A%22STMPUSEMST%22%2C%22startDtm%22%3A%22%22%2C%22startUser%22%3A%22%22%7D&userId=DANGHUI', {
    method: 'GET',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded',
    }
  }).then((response) => response.json())
      .then((responseJson) => {

        var loaded = 0;
        if (responseJson.rows.length < 20) {
            loaded = 2;
        }

        var dataList = this.state.dataList; //列表原始数据
        var page = this.state.page;   //当前页

        if (covered) {
          dataList = responseJson.rows;
        } else {
          dataList = dataList.concat(responseJson.rows);
        }
        page++;
        // var message = JSON.stringify(dataList);
        // AlertIOS.alert(this.state.page+'')
        // AlertIOS.alert(JSON.stringify(dataList));

        this.setState({isRefreshing:false,
         loaded:loaded,
          dataSource:this.state.dataSource.cloneWithRows(dataList),
          dataList:dataList,
          page:page});
      })
      .catch((error) => {
        this.setState({isRefreshing:false, loaded:0});
        console.error(error);
      });
  }

  //  网络请求 React Native提供了和web标准一致的Fetch API，用于满足开发者访问网络的需求,要从任意地址获取内容的话，只需简单地将网址作为参数传递给fetch方法即可
  _headerRefresh() {
    this.setState({isRefreshing:true, page:1}, () => {this._loadData(true)});
  }

  //跳转
  _previewWorkInfo(rowData) {
    this.props.navigator.push({
      title:'待办详情',
      component:WorkflowDetail,
      passProps:{
        gmId:rowData.pgmId,
        pkValue:rowData.pkValue,
        tblName:rowData.tblName,
        pgmNam:rowData.pgmNam
      }
    })
  }

   // 数据列表
  cellForRow(rowData) {
    return (
          <TouchableHighlight underlayColor='gray' onPress={this._previewWorkInfo.bind(this,rowData)}>
            <View style={styles.row}>
              <View style={styles.content}>
                <View style={styles.containerLeft}>
                    <Text style={styles.rowNameText}>
                      {rowData.startUsrId}
                    </Text>
                    <Text style={styles.rowNodeText}>
                      {rowData.nodeSht}
                    </Text>
                    <Text style={styles.rowNameText}>
                      {rowData.arrivedDtm}
                    </Text>
                    <Text style={styles.rowContentText} numberOfLines={1}>
                      {rowData.content}
                    </Text>
                </View>
                <Image style={styles.containerArrow} source={require( '../img/workflow_arrow.png')} />
              </View>
              <View style={styles.bottomLine}>
              </View>
            </View>
          </TouchableHighlight>
    );
  }

  _renderFooter() {

    if (this.state.loaded == 0) {
      // return (<View style={{height:0}}></View>);
    } else if (this.state.loaded == 1) {
      return (
          <View style={{backgroundColor:'white', height:40, flexDirection:'row', justifyContent:'center', alignItems:'center'}}>
            <ActivityIndicator animating={true} size='small' />
            <Text style={{textAlign:'center', color:'gray', marginLeft:10}}>正在加载</Text>
          </View>
        );
    } else if (this.state.loaded == 2) {
      return (
        <View style={{backgroundColor:'white', height:40, justifyContent:'center'}}>
          <Text style={{textAlign:'center', color:'gray'}}>加载完成</Text>
        </View>
      );
    }
  }
  render() {
    return (
      <View style={{flex: 1}}>
        <ListView
          enableEmptySections={true}
          dataSource={this.state.dataSource}
          renderRow={this.cellForRow.bind(this)}
          renderFooter={this._renderFooter.bind(this)}
          onEndReached={this.onEndReached.bind(this)}
          onEndReachedThreshold={-40}
          refreshControl={
                    <RefreshControl
                      refreshing={this.state.isRefreshing}
                      onRefresh={this._headerRefresh.bind(this)}
                      tintColor="#3399FF"
                      title="正在加载数据"
                      titleColor="#3399FF"
                      colors={['#ff0000', '#00ff00', '#0000ff']}
                      progressBackgroundColor="#ffff00"
                    />
                  }
        />
      </View>
    )
  }
}

//定义样式,常见的做法是按顺序声明和使用style属性，以借鉴CSS中的“层叠”做法（即后声明的属性会覆盖先声明的同名属性）。
const styles = StyleSheet.create({
    container:{
      flex:1,
    },
    row:{
      height:60,
    },
    content:{
      flex:1,
      flexDirection:'row',
      justifyContent:'flex-start',
      alignItems:'center',
    },
    containerLeft:{
      flex:13,
      flexDirection:'row',
      flexWrap:'wrap',
      alignItems:'center',
      overflow:'hidden',
      paddingTop:5,
      paddingBottom:5,
    },
    containerArrow:{
      flex:1,
      height:25,
    },
    rowNameText:{
      width:100,
      fontSize:14,
      marginLeft:10,
    },
    rowNodeText:{
      flex:1,
      fontSize:14,
      minWidth:100,
      marginLeft:10,
    },
    rowContentText:{
      width:300,
      fontSize:14,
      marginLeft:10,
      overflow:'hidden',
    },
    bottomLine:{
      height:1,
      marginLeft:10,
      backgroundColor:'lightgray',
    }
});
